import _ from 'lodash';
import { Tooltip, message } from 'antd';
import MyIcon from '@/components/MyIcon';
import pageStyles from '@/common/pageLayout.less';
import { downloadTemplate, getColorTextLoadMap, getFileNameNotType, splitFileUrl, tooltipLength } from '@/utils';

/** 自动匹配value值 */
export const findValueFun = (arr, value, key = 'name') => {
  // 遍历数组中的每个对象
  for (let obj of arr) {
    // 检查当前对象的 value 属性是否等于给定的 value
    if (obj.value == value) {
      // 如果找到匹配的对象，则返回该对象的 key 属性
      return obj[key];
    }
  }
  // 如果没有找到匹配的对象，则返回 '--
  return '--';
};

/** 排序 */
export const getSorter = (prev: Record<string, any>, next: Record<string, any>): number => (prev > next ? 1 : -1);

/** columns内容渲染的方法【文本】ColumnsRenderFun({ text }) */
export const ColumnsRenderFun = ({ text, isTooltip = false, textStyle = {}, event = undefined, record = {}, wordNum = 100 }: Record<string, any>) => {
  return (
    <>
      <Tooltip title={isTooltip ? tooltipLength(text, wordNum) : undefined}>
        <span className={pageStyles['over-flow-hidden']} onClick={event ? () => event(record) : undefined} style={textStyle}>
          {text == null || text == undefined || text == '' ? '--' : text}
        </span>
      </Tooltip>
    </>
  );
};

/** columns内容渲染的方法【字典】DictionaryRenderFun({ text }) 单个 */
export const DictionaryRenderFun = ({
  text,
  isTooltip = false,
  textStyle = {},
  event = undefined,
  record = {},
  wordNum = 100,
  isState = false,
}: Record<string, any>) => {
  const { colorText, color } = getColorTextLoadMap(text);
  return (
    <>
      <Tooltip title={isTooltip ? tooltipLength(colorText, wordNum) : undefined}>
        <span
          className={pageStyles['over-flow-hidden']}
          onClick={event ? () => event(record) : undefined}
          style={{ color: isState ? null : color, ...textStyle }}
        >
          {isState && text ? (
            <>
              <MyIcon type="icon-dian" style={{ color }} />
              &nbsp;
            </>
          ) : (
            <></>
          )}
          {colorText == null || colorText == undefined || colorText == '' ? '--' : colorText}
        </span>
      </Tooltip>
    </>
  );
};

/** columns内容渲染的方法【字典】DictionaryRenderFun({ text }) 多个，用/隔开 */
export const DictionaryRenderFuns = ({
  text,
  isTooltip = false,
  textStyle = {},
  event = undefined,
  record = {},
  wordNum = 50,
  isState = false,
}: Record<string, any>) => {
  const { color } = getColorTextLoadMap(text);
  const items = text?.split(',');
  const names = items?.map((item) => item?.split('||')?.[0]);
  return (
    <>
      <Tooltip title={isTooltip ? tooltipLength(names?.join('/'), wordNum) : undefined}>
        <span className={pageStyles['over-flow-hidden']} onClick={event ? () => event(record) : undefined} style={{ ...textStyle }}>
          {isState && text ? (
            <>
              <MyIcon type="icon-dian" style={{ color }} />
              &nbsp;
            </>
          ) : (
            <></>
          )}
          {names?.join('/')}
        </span>
      </Tooltip>
    </>
  );
};

/** 判断值是否有两位小数点，没有则自动补零 */
export const formatDecimal = (val: any) => {
  // 不存在的话就返回'--'
  if (!val) return '0.00';
  // 将输入值转为数字，以确保处理的是数值类型
  const num = Number(val);
  // 如果转换后的数值是NaN，则直接返回原始值
  if (isNaN(num)) return '0.00';
  // 使用toFixed方法确保小数点后有两位，然后再转回字符串
  return num.toFixed(2) + '';
};

/** 展示文件 */
export const renderFileFunc = ({ record, fileName, downloadAddress, returnStr = '--' }) => {
  if (!record?.[fileName]) return returnStr;
  return (
    <>
      {record?.[fileName] && splitFileUrl(record?.[fileName]).length > 0
        ? splitFileUrl(record?.[fileName])?.map((e, i) => {
            return (
              <Tooltip title={e.attachName} key={new Date().getTime() * 155214525515 + e?.attachName}>
                <a
                  onClick={() => {
                    message.success('下载中，请稍后...');
                    downloadTemplate(downloadAddress, e?.attachName, e?.attachUrl, () => {});
                  }}
                >
                  <MyIcon type="icon-file-text-fill" />
                  &nbsp;
                  {getFileNameNotType(e.attachName, 8)}
                </a>
              </Tooltip>
            );
          })
        : returnStr}
    </>
  );
};

/** 判断假值的方法 */
export const isFalsy = (value: any) => {
  if (value === null || value === undefined || value === 0 || value === false) {
    return false;
  } else if (typeof value === 'string' && (value.toLowerCase() === 'null' || isNaN(value as any))) {
    return false;
  } else {
    return true;
  }
};

/** 处理搜索条件 */
export const searchCriteriaFun = (resObj_s) => {
  if (!resObj_s) return {};

  /**申请人、部门处理*/
  if (resObj_s?.applyFormNameDept || resObj_s?.applyFormNameUser) {
    delete resObj_s['applyFormNameDept'];
    delete resObj_s['applyFormNameUser'];
    if (resObj_s?.applyerID && resObj_s?.applyerID?.length > 0) {
      resObj_s['applyerID'] = resObj_s?.applyerID?.toString();
    } else {
      delete resObj_s['applyerID'];
    }
  }

  /**创建人、部门处理*/
  if (resObj_s?.createFormNameDept || resObj_s?.createFormNameUser) {
    delete resObj_s['createFormNameDept'];
    delete resObj_s['createFormNameUser'];
    if (resObj_s?.createrID && resObj_s?.createrID?.length > 0) {
      resObj_s['createrID'] = resObj_s?.createrID?.toString();
    } else {
      delete resObj_s['createrID'];
    }
  }

  /** 申请时间处理 */
  if (resObj_s?.applyTime) {
    const [applyTimeStart, applyTimeEnd] = resObj_s.applyTime;
    resObj_s['applyTimeStart'] = applyTimeStart.format('YYYY-MM-DD 00:00:00');
    resObj_s['applyTimeEnd'] = applyTimeEnd.format('YYYY-MM-DD 23:59:59');
    delete resObj_s['applyTime'];
  }

  /** 创建时间处理 */
  if (resObj_s?.createTime) {
    const [createTimeStart, createTimeEnd] = resObj_s.createTime;
    resObj_s['createTimeStart'] = createTimeStart.format('YYYY-MM-DD 00:00:00');
    resObj_s['createTimeEnd'] = createTimeEnd.format('YYYY-MM-DD 23:59:59');
    delete resObj_s['createTime'];
  }

  /** 作废时间处理 */
  if (resObj_s?.cancelTime) {
    const [cancelTimeStart, cancelTimeEnd] = resObj_s.cancelTime;
    resObj_s['cancelTimeStart'] = cancelTimeStart.format('YYYY-MM-DD 00:00:00');
    resObj_s['cancelTimeEnd'] = cancelTimeEnd.format('YYYY-MM-DD 23:59:59');
    delete resObj_s['cancelTime'];
  }

  return resObj_s;
};
